package com.example.socialapp.ui.auth.register

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Email
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Phone
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * 注册界面
 *
 * @param viewModel 注册视图模型
 * @param onNavigateToMain 导航到主界面
 * @param onNavigateToLogin 导航到登录界面
 * @param onNavigateToTerms 导航到条款界面
 * @param onGoogleSignIn 使用Google登录
 * @param onFacebookSignIn 使用Facebook登录
 * @param onAppleSignIn 使用Apple登录
 */
@Composable
fun RegisterScreen(
    viewModel: RegisterViewModel,
    onNavigateToMain: () -> Unit,
    onNavigateToLogin: () -> Unit,
    onNavigateToTerms: () -> Unit,
    onGoogleSignIn: () -> Unit,
    onFacebookSignIn: () -> Unit,
    onAppleSignIn: () -> Unit
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val snackbarHostState = remember { SnackbarHostState() }
    val scope = rememberCoroutineScope()
    
    // 处理副作用
    LaunchedEffect(key1 = Unit) {
        viewModel.effect.collectLatest { effect ->
            when (effect) {
                is RegisterEffect.NavigateToMain -> onNavigateToMain()
                is RegisterEffect.NavigateToLogin -> onNavigateToLogin()
                is RegisterEffect.NavigateToTerms -> onNavigateToTerms()
                is RegisterEffect.ShowError -> {
                    scope.launch {
                        snackbarHostState.showSnackbar(effect.message)
                    }
                }
                is RegisterEffect.ShowSuccess -> {
                    scope.launch {
                        snackbarHostState.showSnackbar(effect.message)
                    }
                }
                is RegisterEffect.LaunchGoogleSignIn -> onGoogleSignIn()
                is RegisterEffect.LaunchFacebookSignIn -> onFacebookSignIn()
                is RegisterEffect.LaunchAppleSignIn -> onAppleSignIn()
            }
        }
    }
    
    Scaffold(
        snackbarHost = { SnackbarHost(snackbarHostState) }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            RegisterContent(
                state = state,
                onEmailChanged = { viewModel.processIntent(RegisterIntent.UpdateEmail(it)) },
                onPasswordChanged = { viewModel.processIntent(RegisterIntent.UpdatePassword(it)) },
                onConfirmPasswordChanged = { viewModel.processIntent(RegisterIntent.UpdateConfirmPassword(it)) },
                onDisplayNameChanged = { viewModel.processIntent(RegisterIntent.UpdateDisplayName(it)) },
                onPhoneNumberChanged = { viewModel.processIntent(RegisterIntent.UpdatePhoneNumber(it)) },
                onTermsChanged = { viewModel.processIntent(RegisterIntent.ToggleTerms(it)) },
                onRegisterClicked = { viewModel.processIntent(RegisterIntent.SubmitRegister) },
                onLoginClicked = { viewModel.processIntent(RegisterIntent.NavigateToLogin) },
                onTermsClicked = { viewModel.processIntent(RegisterIntent.NavigateToTerms) },
                onGoogleClicked = { viewModel.processIntent(RegisterIntent.RegisterWithGoogle) },
                onFacebookClicked = { viewModel.processIntent(RegisterIntent.RegisterWithFacebook) },
                onAppleClicked = { viewModel.processIntent(RegisterIntent.RegisterWithApple) }
            )
            
            if (state.isLoading) {
                CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
            }
        }
    }
}

/**
 * 注册界面内容
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun RegisterContent(
    state: RegisterState,
    onEmailChanged: (String) -> Unit,
    onPasswordChanged: (String) -> Unit,
    onConfirmPasswordChanged: (String) -> Unit,
    onDisplayNameChanged: (String) -> Unit,
    onPhoneNumberChanged: (String) -> Unit,
    onTermsChanged: (Boolean) -> Unit,
    onRegisterClicked: () -> Unit,
    onLoginClicked: () -> Unit,
    onTermsClicked: () -> Unit,
    onGoogleClicked: () -> Unit,
    onFacebookClicked: () -> Unit,
    onAppleClicked: () -> Unit
) {
    val focusManager = LocalFocusManager.current
    val keyboardController = LocalSoftwareKeyboardController.current
    var passwordVisible by remember { mutableStateOf(false) }
    var confirmPasswordVisible by remember { mutableStateOf(false) }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .verticalScroll(rememberScrollState()),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 应用标题
        Text(
            text = "注册新账号",
            style = MaterialTheme.typography.headlineMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.padding(vertical = 24.dp)
        )
        
        // 用户名输入框
        OutlinedTextField(
            value = state.displayName,
            onValueChange = onDisplayNameChanged,
            label = { Text("昵称") },
            placeholder = { Text("请输入您的昵称") },
            leadingIcon = { Icon(Icons.Default.Person, contentDescription = "昵称") },
            isError = state.isDisplayNameError,
            supportingText = if (state.isDisplayNameError) {
                { Text(state.displayNameErrorMessage) }
            } else null,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Text,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 邮箱输入框
        OutlinedTextField(
            value = state.email,
            onValueChange = onEmailChanged,
            label = { Text("邮箱") },
            placeholder = { Text("请输入您的邮箱") },
            leadingIcon = { Icon(Icons.Default.Email, contentDescription = "邮箱") },
            isError = state.isEmailError,
            supportingText = if (state.isEmailError) {
                { Text(state.emailErrorMessage) }
            } else null,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Email,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 手机号输入框
        OutlinedTextField(
            value = state.phoneNumber,
            onValueChange = onPhoneNumberChanged,
            label = { Text("手机号（选填）") },
            placeholder = { Text("请输入您的手机号") },
            leadingIcon = { Icon(Icons.Default.Phone, contentDescription = "手机号") },
            isError = state.isPhoneNumberError,
            supportingText = if (state.isPhoneNumberError) {
                { Text(state.phoneNumberErrorMessage) }
            } else null,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Phone,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 密码输入框
        OutlinedTextField(
            value = state.password,
            onValueChange = onPasswordChanged,
            label = { Text("密码") },
            placeholder = { Text("请设置密码，不少于6位") },
            leadingIcon = { Icon(Icons.Default.Lock, contentDescription = "密码") },
            trailingIcon = {
                IconButton(onClick = { passwordVisible = !passwordVisible }) {
                    val icon = if (passwordVisible) {
                        Icons.Default.VisibilityOff
                    } else {
                        Icons.Default.Visibility
                    }
                    Icon(icon, contentDescription = "切换密码可见性")
                }
            },
            visualTransformation = if (passwordVisible) {
                VisualTransformation.None
            } else {
                PasswordVisualTransformation()
            },
            isError = state.isPasswordError,
            supportingText = if (state.isPasswordError) {
                { Text(state.passwordErrorMessage) }
            } else null,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        // 确认密码输入框
        OutlinedTextField(
            value = state.confirmPassword,
            onValueChange = onConfirmPasswordChanged,
            label = { Text("确认密码") },
            placeholder = { Text("请再次输入密码") },
            leadingIcon = { Icon(Icons.Default.Lock, contentDescription = "确认密码") },
            trailingIcon = {
                IconButton(onClick = { confirmPasswordVisible = !confirmPasswordVisible }) {
                    val icon = if (confirmPasswordVisible) {
                        Icons.Default.VisibilityOff
                    } else {
                        Icons.Default.Visibility
                    }
                    Icon(icon, contentDescription = "切换密码可见性")
                }
            },
            visualTransformation = if (confirmPasswordVisible) {
                VisualTransformation.None
            } else {
                PasswordVisualTransformation()
            },
            isError = state.isConfirmPasswordError,
            supportingText = if (state.isConfirmPasswordError) {
                { Text(state.confirmPasswordErrorMessage) }
            } else null,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(
                onDone = {
                    keyboardController?.hide()
                    onRegisterClicked()
                }
            ),
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 条款协议
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Checkbox(
                checked = state.acceptedTerms,
                onCheckedChange = onTermsChanged
            )
            
            val annotatedString = buildAnnotatedString {
                append("我已阅读并同意")
                
                pushStringAnnotation(tag = "terms", annotation = "terms")
                withStyle(
                    style = SpanStyle(
                        color = MaterialTheme.colorScheme.primary,
                        textDecoration = TextDecoration.Underline
                    )
                ) {
                    append("用户协议")
                }
                pop()
                
                append("和")
                
                pushStringAnnotation(tag = "privacy", annotation = "privacy")
                withStyle(
                    style = SpanStyle(
                        color = MaterialTheme.colorScheme.primary,
                        textDecoration = TextDecoration.Underline
                    )
                ) {
                    append("隐私政策")
                }
                pop()
            }
            
            Text(
                text = annotatedString,
                modifier = Modifier.clickable { onTermsClicked() }
            )
        }
        
        if (state.isTermsError) {
            Text(
                text = state.termsErrorMessage,
                color = MaterialTheme.colorScheme.error,
                style = MaterialTheme.typography.bodySmall,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(24.dp))
        
        // 注册按钮
        Button(
            onClick = {
                keyboardController?.hide()
                onRegisterClicked()
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text("注册")
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 已有账号
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text("已有账号？")
            TextButton(onClick = onLoginClicked) {
                Text("立即登录")
            }
        }
        
        Spacer(modifier = Modifier.height(24.dp))
        
        // 社交登录分割线
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Divider(
                modifier = Modifier.weight(1f),
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
            )
            Text(
                text = "使用以下方式注册",
                modifier = Modifier.padding(horizontal = 8.dp),
                color = MaterialTheme.colorScheme.outline
            )
            Divider(
                modifier = Modifier.weight(1f),
                color = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
            )
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 社交登录按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            SocialButton(
                text = "谷歌",
                onClick = onGoogleClicked,
                modifier = Modifier.weight(1f)
            )
            
            Spacer(modifier = Modifier.size(8.dp))
            
            SocialButton(
                text = "脸书",
                onClick = onFacebookClicked,
                modifier = Modifier.weight(1f)
            )
            
            Spacer(modifier = Modifier.size(8.dp))
            
            SocialButton(
                text = "苹果",
                onClick = onAppleClicked,
                modifier = Modifier.weight(1f)
            )
        }
        
        Spacer(modifier = Modifier.height(32.dp))
    }
}

/**
 * 社交登录按钮
 */
@Composable
private fun SocialButton(
    text: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    OutlinedButton(
        onClick = onClick,
        modifier = modifier
    ) {
        Text(
            text = text,
            textAlign = TextAlign.Center
        )
    }
} 